<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同编号" prop="contractCode">
        <el-input
          v-model="queryParams.contractCode"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同状态" prop="approveStatus">
        <el-select v-model="queryParams.approveStatus" placeholder="请选择合同状态" clearable>
          <el-option
            v-for="dict in dict.type.pur_plan_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sale:contract:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sale:contract:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sale:contract:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-top-right"
          size="mini"
          :disabled="multiple"
          @click="handleCommit"
          v-hasPermi="['sale:contract:commit']"
        >提交
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-bottom-left"
          size="mini"
          :disabled="multiple"
          @click="handleRecall"
          v-hasPermi="['sale:contract:recall']"
        >撤回
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contractList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" align="center" prop="contractId"/>
      <el-table-column label="合同编号" align="center" prop="contractCode" width="200"/>
      <el-table-column label="合同名称" align="center" prop="contractName" width="200"/>
      <el-table-column label="合同状态" align="center" prop="approveStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pur_plan_status" :value="scope.row.approveStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="合同金额" align="center" prop="total"/>
      <el-table-column label="审批人" align="center" prop="approver"/>
      <el-table-column label="审批时间" align="center" prop="approveTime" width="160"/>
      <el-table-column label="审批意见" align="center" prop="approveOpinion" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="创建者" align="center" prop="createBy" width="120"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sale:contract:edit']"
            v-show="scope.row.approveStatus==0"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sale:contract:remove']"
            v-show="scope.row.approveStatus==0"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleQueryBody(scope.row)"
            v-show="scope.row.approveStatus!=0"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-top-right"
            @click="handleCommit(scope.row)"
            v-hasPermi="['sale:contract:commit']"
            v-show="scope.row.approveStatus==0"
          >提交
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-bottom-left"
            @click="handleRecall(scope.row)"
            v-hasPermi="['sale:contract:recall']"
            v-show="scope.row.approveStatus==1"
          >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['sale:contract:approve']"
            v-show="scope.row.approveStatus==1"
          >审批
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-warning"
            @click="handleUnapprove(scope.row)"
            v-hasPermi="['sale:contract:unapprove']"
            v-show="scope.row.approveStatus==2 || scope.row.approveStatus==3"
          >弃审
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="form.contractCode" placeholder="合同编号自动生成" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customer">
              <el-input v-model="form.customer" placeholder="请输入客户名称"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider>销售合同子表信息</el-divider>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAddLine"
          >增行
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="handleDeleteLine"
          >删行
          </el-button>
        </el-col>
      </el-row>

      <el-table :data="form.contractBodyList" :row-class-name="rowContractBodyIndex"
                @selection-change="handleContractBodySelectionChange"
      >
        <el-table-column type="selection" width="80" align="center"/>
        <el-table-column label="序号" align="center" prop="index" width="120"/>
        <el-table-column label="存货管理" align="center" prop="inventoryId" width="220">
          <template slot-scope="scope">
            <el-select v-model="scope.row.inventoryId" placeholder="请选择存货管理">
              <el-option
                v-for="inventory in inventoryOptions"
                :key="inventory.inventoryId"
                :label="inventory.inventoryName"
                :value="inventory.inventoryId"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="销售数量" align="center" prop="saleNumber" width="220">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.saleNumber" :precision="2" :step="1" :min="0"/>
          </template>
        </el-table-column>
        <el-table-column label="销售单价" align="center" prop="salePrice" width="220">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.salePrice" :precision="2" :step="1" :min="0"/>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看合同对话框 -->
    <el-dialog title="查看合同" :visible.sync="bodyOpen" width="900px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="form.contractCode" placeholder="合同编号自动生成" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customer">
              <el-input v-model="form.customer" placeholder="请输入客户名称" :disabled="true"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider>销售合同子表信息</el-divider>
      <el-table :data="form.contractBodyList" :row-class-name="rowContractBodyIndex">
        <el-table-column label="序号" align="center" prop="index" width="120"/>
        <el-table-column label="存货管理" align="center" prop="inventoryId" width="300">
          <template slot-scope="scope">
            <span v-for="inventory in inventoryOptions">
              <span v-if="scope.row.inventoryId===inventory.inventoryId">{{ inventory.inventoryName }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="销售数量" align="center" prop="saleNumber" width="220"/>
        <el-table-column label="销售单价" align="center" prop="salePrice" width="220"/>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBody">关 闭</el-button>
      </div>
    </el-dialog>

    <!--审批对话框 -->
    <el-dialog title="审批合同" :visible.sync="approveOpen" width="900px" append-to-body>
      <el-form ref="form" :model="approveForm" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审批结果" prop="approveResult">
              <el-select v-model="approveForm.approveResult" placeholder="请选择审批结果">
                <el-option
                  v-for="approve in approveOptions"
                  :key="approve.key"
                  :label="approve.label"
                  :value="approve.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审批意见" prop="approveOpinion">
              <el-input v-model="approveForm.approveOpinion" type="textarea" :rows="5" placeholder="请输入审批意见"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApproveForm">确 定</el-button>
        <el-button @click="cancelApprove">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addContract,
  approveContract,
  commitContract,
  delContract,
  getContract,
  listContract,
  recallContract,
  unapproveContract,
  updateContract
} from '@/api/sale/contract'
import { listInventory } from '@/api/archive/inventory'

export default {
  name: 'Contract',
  dicts: ['pur_plan_status', 'sys_contract_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同表格数据
      contractList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractCode: undefined,
        contractName: undefined,
        approveStatus: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractName: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' }
        ]
      },
      // 存货选项
      inventoryOptions: [],
      // 子表选择集合
      checkedBodyList: [],
      // 查看对话框是否显示
      bodyOpen: false,
      // 审批对话框是否显示
      approveOpen: false,
      approveForm: {
        contractId: undefined,
        approveResult: undefined,
        approveOpinion: undefined
      },
      approveOptions: [
        { key: 'pass', label: '同意' },
        { key: 'nopass', label: '不同意' },
        { key: 'reject', label: '驳回' }
      ]
    }
  },
  created() {
    this.getList()
    this.getInventoryList()
  },
  methods: {
    getInventoryList() {
      listInventory().then(res => {
        this.inventoryOptions = res.data
      })
    },
    /** 查询合同列表 */
    getList() {
      this.loading = true
      listContract(this.queryParams).then(response => {
        this.contractList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: undefined,
        contractCode: undefined,
        contractName: undefined,
        customer: undefined,
        contractBodyList: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加合同'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const contractId = row.contractId || this.ids
      getContract(contractId).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改合同'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.contractId != undefined) {
            updateContract(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addContract(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids
      this.$modal.confirm('是否确认删除合同编号为"' + contractIds + '"的数据项？').then(function() {
        return delContract(contractIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 增行按钮操作 */
    handleAddLine() {
      const obj = {}
      obj.inventoryId = undefined
      obj.saleNumber = '0.00'
      obj.salePrice = '0.00'
      this.form.contractBodyList.push(obj)
    },
    /** 删行按钮操作 */
    handleDeleteLine() {
      if (this.checkedBodyList.length === 0) {
        this.$modal.msgError('请先选中需要删除的销售合同子信息')
      } else {
        const contractBodyList = this.form.contractBodyList
        const checkedBodyList = this.checkedBodyList
        this.form.contractBodyList = contractBodyList.filter(function(item) {
          return checkedBodyList.indexOf(item.index) === -1
        })
      }
    },
    /** 显示子表序号 */
    rowContractBodyIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 销售合同子表选择事件 */
    handleContractBodySelectionChange(selection) {
      this.checkedBodyList = selection.map(item => item.index)
    },
    /** 提交按钮方法 */
    handleCommit(row) {
      if (row.contractId !== undefined) {
        this.ids = []
        this.ids.push(row.contractId)
      }
      const contractIds = this.ids
      this.$modal.confirm('是否确认提交序号为"' + contractIds + '"的数据项？').then(function() {
        return commitContract(contractIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('提交成功')
      }).catch(() => {
      })
    },
    /** 查看按钮方法 */
    handleQueryBody(row) {
      this.reset()
      getContract(row.contractId).then(response => {
        this.form = response.data
        this.bodyOpen = true
      })
    },
    /** 查看关闭按钮方法 */
    cancelBody() {
      this.bodyOpen = false
    },
    /** 撤回按钮方法 */
    handleRecall(row) {
      if (row.contractId !== undefined) {
        this.ids = []
        this.ids.push(row.contractId)
      }
      const contractIds = this.ids
      this.$modal.confirm('是否确认提交序号为"' + contractIds + '"的数据项？').then(function() {
        return recallContract(contractIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('撤回成功')
      }).catch(() => {
      })
    },
    /** 审批按钮方法 */
    handleApprove(row) {
      this.approveForm.contractId = row.contractId
      this.approveForm.approveResult = 'pass'
      this.approveForm.approveOpinion = undefined
      this.approveOpen = true
    },
    /** 审批确定按钮方法 */
    submitApproveForm() {
      approveContract(this.approveForm).then(res => {
        this.approveOpen = false
        this.getList()
        this.$modal.msgSuccess('审批成功')
      }).catch(() => {
      })
    },
    /** 审批取消按钮方法 */
    cancelApprove() {
      this.approveOpen = false
    },
    /** 弃审按钮方法 */
    handleUnapprove(row) {
      this.$modal.confirm('是否确认弃审序号为"' + row.contractId + '"的数据项？').then(function() {
        return unapproveContract(row)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('弃审成功')
      }).catch(() => {
      })
    }
  }
}
</script>
